#!/bin/sh

# Function to manage service startup and enable on boot
manage_service() {
    service_name="$1"
    if systemctl is-active --quiet "$service_name"; then
        echo "$service_name is already running"
    else
        echo "$service_name is not running, starting..."
        if systemctl start "$service_name" && systemctl enable "$service_name"; then
            echo "$service_name starting success."
        else
            echo "Unable to start $service_name."
            exit 1
        fi
    fi
}

# Check if service exists and manage it
check_and_manage_service() {
    service_name="$1"
    if systemctl list-unit-files | grep -q "$service_name.service"; then
        manage_service "$service_name"
    else
        echo "$service_name service does not exist, skipping..."
    fi
}

check_and_manage_service "{{.Runtime}}"
check_and_manage_service "housekeeper-daemon"

# Configure the crio container runtime
if [ -f "/etc/crio/crio.conf" ]; then
    if [ "{{.Runtime}}" = "crio" ]; then
        if grep -q "\[crio\.image\]" /etc/crio/crio.conf; then
            if grep -q "^[[:space:]]*pause_image = " /etc/crio/crio.conf; then
                sed -i 's|^pause_image = .*|pause_image = "{{.ImageRegistry}}/{{.PauseImage}}"|' /etc/crio/crio.conf
            else
                sed -i '/\[crio\.image\]/a pause_image = "{{.ImageRegistry}}/{{.PauseImage}}"' /etc/crio/crio.conf
            fi
        else
            echo "[crio.image]" >> /etc/crio/crio.conf
            echo "pause_image = \"{{.ImageRegistry}}/{{.PauseImage}}\"" >> /etc/crio/crio.conf
        fi
        systemctl restart crio
    fi
fi

# Disable SELinux
echo "Disabling SELinux..."
sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config
setenforce 0

# Check if ReleaseImageURl is empty
if [ -n "{{.ReleaseImageURl}}" ]; then
    # Execute rebase
    rpm-ostree rebase --experimental ostree-unverified-image:docker://{{.ReleaseImageURl}} --bypass-driver
    # Check if the rebase was successful
    if [ $? -eq 0 ]; then
        echo "Rebase operation completed successfully. Rebooting the system..."
        systemctl reboot
    else
        echo "Rebase operation failed. System will not be rebooted."
    fi

else
    echo "ReleaseImageURl is empty, skipping rpm-ostree rebase."
fi
